/*=============================================================================================================
 * MainActivity.java
 *
 * 1.프로젝트 : ToYou - 명함관리 어플
 * 2.패 키 지 : com.trillion.toyou
 * 3.작업환경 : Android
 * 2.작 업 자 : 손호준, 최명식
 * 3.작업일자 : 2014.12.09 ~ 2014.12.12
 * 4.내    용 : 
 * (1) 프래그먼트들을 띄우는 엑티비티
 * (2) 전송할 명함과 받은 명함 저장
 * (3) nfc 기능
 * (4) 백키 제어
 * 
 * 5.수 정 자 : -----
 * 6.수정일자 : -----
 * 7.수정내용 : -----
 * 
 * =============================================================================================================*/
package com.trillion.toyou;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcAdapter.CreateNdefMessageCallback;
import android.nfc.NfcAdapter.OnNdefPushCompleteCallback;
import android.nfc.NfcEvent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.Toast;


public class MainActivity extends Activity implements CreateNdefMessageCallback, OnNdefPushCompleteCallback {
	static int page_check = 0;				// back 키 이벤트 제어
	static Data my_main_namecard = null;	// 대표명함
	static Data catch_namecard = null;		// 받은명함
	static NfcAdapter nfcAdapter = null;	// NFC
	static String category_choice ="";  	// 선택된 카테고리
	static int sort_choice = 0;			// 선택된 정렬방식
	

	final int BACK_OK = 101;				// back 허용
	final int BACK_EXIT = 102;				// 종료
	final int BACK_LIST = 103;				// 리스트 화면으로 전환
	final int BACK_MYLIST = 104;			// 내 명함 리스트 화면으로 전환
	
	

	private Fragment frag = null;
	private FragmentTransaction trans = null;
	
	private Handler mh;
	private Runnable mr;
	
	
	private boolean check = true;
	private long startTime = 0;
	private long endTime = 0;

	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		
		this.nfcAdapter = nfcAdapter.getDefaultAdapter(this);
		
		if(this.nfcAdapter != null){
			this.nfcAdapter.setNdefPushMessageCallback(this, this);
			this.nfcAdapter.setOnNdefPushCompleteCallback(this, this);
			
		}else{
			Toast.makeText(this, "현 기기는 NFC를 지원하지 않습니다.", Toast.LENGTH_SHORT).show();
		}
				

		
		
		this.trans = getFragmentManager().beginTransaction();
		this.frag = new LogoFragment();
		this.trans.replace(R.id.root_layout, frag);
		this.trans.addToBackStack(null);
		this.trans.commitAllowingStateLoss();
		
		mr = new Runnable() {
			
			private FragmentTransaction trans;
			private ListFragment frag;

			@Override
			public void run() {
				this.trans = getFragmentManager().beginTransaction();
				this.frag = new ListFragment();
				this.trans.replace(R.id.root_layout, frag);
				this.trans.addToBackStack(null);
				this.trans.commitAllowingStateLoss();
				
			}
		};
		mh = new Handler();
		mh.postDelayed(mr, 2300);		
		
	}
	
	@Override
	protected void onDestroy() {
		mh.removeCallbacks(mr);
		super.onDestroy();
	}

	
	
	@Override
	protected void onResume() {
		if(NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())){
			receiveMsg(getIntent());
		}
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
	}
	
	
	public void receiveMsg(Intent intent){
		Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
				NfcAdapter.EXTRA_NDEF_MESSAGES);
		
		NdefMessage msg = (NdefMessage) rawMsgs[0];
		
		catch_namecard = new Data();
		
		catch_namecard.setNname(new String(msg.getRecords()[0].getPayload()));
		catch_namecard.setGrade(new String(msg.getRecords()[1].getPayload()));
		catch_namecard.setDepartment(new String(msg.getRecords()[2].getPayload()));
		catch_namecard.setCompany(new String(msg.getRecords()[3].getPayload()));
		catch_namecard.setPhoneNum(new String(msg.getRecords()[4].getPayload()));
		catch_namecard.setTelNum(new String(msg.getRecords()[5].getPayload()));
		catch_namecard.setEmail(new String(msg.getRecords()[6].getPayload()));
		catch_namecard.setAddress(new String(msg.getRecords()[7].getPayload()));
		catch_namecard.setStyleId(Integer.parseInt(new String(msg.getRecords()[8].getPayload())));
		
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		setIntent(intent);
	}
	
	
	@Override
	public NdefMessage createNdefMessage(NfcEvent event) {
		if(this.my_main_namecard != null){
//			NdefMessage massage = new NdefMessage(new NdefRecord[] {createTextRecord(my_main_namecard.getNid()+""),createTextRecord(my_main_namecard.getNname())});
			NdefMessage massage = new NdefMessage(new NdefRecord[] {createTextRecord(my_main_namecard.getNname()),
																	 createTextRecord(my_main_namecard.getGrade()),
																	 createTextRecord(my_main_namecard.getDepartment()),
																	 createTextRecord(my_main_namecard.getCompany()),
																	 createTextRecord(my_main_namecard.getPhoneNum()),
																	 createTextRecord(my_main_namecard.getTelNum()),
																	 createTextRecord(my_main_namecard.getEmail()),
																	 createTextRecord(my_main_namecard.getAddress()),
																	 createTextRecord(my_main_namecard.getStyleId()+"")});

			return massage;
		}else{
			return null;
		}
		
	}

	@Override
	public void onNdefPushComplete(NfcEvent event) {
		mHandler.obtainMessage(1).sendToTarget();

	}

	public NdefRecord createTextRecord(String text) {

		byte[] data = text.getBytes();
		return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT,
				new byte[0], data);
	}


	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Toast.makeText(getApplicationContext(), "전송완료", Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};

	
	
	
	
	

	
	
	
	// back 키 이벤트 적용
	@Override
	public void onBackPressed() {
		FragmentTransaction trans = null;
		Fragment frag = null;
		switch(page_check)
		{
		case BACK_OK:
			super.onBackPressed();
		break;
		
		
		case BACK_EXIT:
			if(check){
				startTime = System.currentTimeMillis();
			
				Toast.makeText(this, "'뒤로'버튼을 한번 더 누르면 종료됩니다.", Toast.LENGTH_SHORT).show();
				
				check = false;
			
			} else{
				endTime = System.currentTimeMillis();
				
				if((endTime - startTime) < 2000){
					finish();
				}else{
					startTime = System.currentTimeMillis();
					
					Toast.makeText(this, "'뒤로'버튼을 한번 더 누르면 종료됩니다.", Toast.LENGTH_SHORT).show();
				}
			}
		break;
		
		
		case BACK_LIST:
			trans = getFragmentManager().beginTransaction();
			frag = new ListFragment();
			
			trans.replace(R.id.root_layout, frag);
			trans.addToBackStack(null);
			trans.commitAllowingStateLoss();
			
		break;	
		
		case BACK_MYLIST:
			trans = getFragmentManager().beginTransaction();
			frag = new MyFragment();
			
			trans.replace(R.id.root_layout, frag);
			trans.addToBackStack(null);
			trans.commitAllowingStateLoss();
			
		break;	
		}
		
	}
	

	
	
	
	
	// 기본 옵션메뉴는 사용하지 않습니다.
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		return super.onOptionsItemSelected(item);
	}


	
}
